﻿#region MIT
/*
Engine Of Evermore (http://code.google.com/p/engineofevermore/)
Copyright (c) 2008, 2009 Michael Woerister

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Diagnostics;
using System.Xml.Linq;
using System.ComponentModel;
using System.Reflection;
using Blue.ResourceManager;
using Green.Logging;
using EngineOfEvermore.Common;

namespace EngineOfEvermore.Imaging
{
    public class ImageMap : DisposableResource
    {
        #region Fields
        IFrameGenerator _frameGenerator;
        bool _disposed;
        List<ImageMapFrame> _frames;
        String _imageName;
        Size _atlasSize;
        #endregion

        #region Properties
        /// <summary>
        /// The Resource Name of the image to use.
        /// </summary>
        public String ImageName 
        {
            get { return _imageName; }
            private set { _imageName = value; }
        }

        public IFrameGenerator FrameGenerator
        {
            get { return _frameGenerator; }
            private set { _frameGenerator = value; }
        }

        public int FrameCount
        {
            get { return _frames.Count; }
        }
        #endregion

        #region Constructor
        private ImageMap( String name ):
            base( name )
        {

        }
        #endregion

        #region Methods
        public Size GetFrameSize( int frameIndex )
        {
            return _frames[frameIndex].OriginalArea.Size;
        }

        public int FindFrameAtPosition( Point position )
        {
            for ( int i = 0; i < _frames.Count; ++i )
            {
                if ( _frames[i].OriginalArea.Contains( position ) )
                {
                    return i;
                }
            }

            return -1;
        }

        public static void LoadFromXmlStream(
            Stream stream,
            out IFrameGenerator frameGenerator,
            out String imageName,
            out Size? sizeHint )
        {
            var sizeConverter = TypeDescriptor.GetConverter( typeof( Size ) );
			
            Debug.Assert( sizeConverter.CanConvertFrom( typeof( String ) ) );

            XDocument doc = XDocument.Load( new StreamReader( stream ) );

            imageName = (String) ( doc.Descendants( "ImageName" ).Single() );
            imageName = ResourceManager.NormalizeName( imageName );

            sizeHint = null;

            XElement atlasSizeElement =
                doc.Descendants( "AtlasSizeHint" ).SingleOrDefault();

            if ( atlasSizeElement != null )
            {
				try
				{
					sizeHint = (Size) sizeConverter
                        .ConvertFromInvariantString( atlasSizeElement.Value );
				}
				catch
				{
					sizeHint = null;
				}
            }

            XElement frameGeneratorElement = doc.Descendants( "FrameGenerator" ).Single();
            String frameGeneratorXmlName = frameGeneratorElement.Attribute( "type" ).Value;

            frameGenerator =
                ImageMap.CreateFrameGenerator( frameGeneratorXmlName );

            frameGenerator.LoadFromXmlRepresentation( frameGeneratorElement );
        }

        public static ImageMap LoadFromXmlStream( String resourceName, Stream stream )
        {
            Size? sizeHint;
            String imageName;
            IFrameGenerator frameGenerator;

            LoadFromXmlStream( stream, out frameGenerator, out imageName, out sizeHint );

            ImageMap imageMap = new ImageMap( resourceName );
            imageMap.ImageName = imageName;
            imageMap.FrameGenerator = frameGenerator;

            using ( Stream imageStream = ResourceManager.OpenStream( imageName, 
                ResourceOpenMode.Read ) )
            {
                using ( Bitmap bitmap = new Bitmap( imageStream ) )
                {
					bitmap.MakeTransparent();
					
					imageMap._packImage( 
                        bitmap, 
                        frameGenerator.GenerateFrames( bitmap ), 
                        sizeHint 
                        );
                }
            }

            return imageMap;
        }

        public static void SaveAsResource( 
            String resourceName,
            IFrameGenerator frameGenerator,
            String imageName,
            Size? sizeHint )
        {
            Debug.Assert( frameGenerator != null );
            Debug.Assert( ResourceManager.ResourceExists( imageName ) );

            ImageMap imageMap = new ImageMap( resourceName );
            imageMap.ImageName = imageName;
            imageMap.FrameGenerator = frameGenerator;

            if ( sizeHint.HasValue )
            {
                imageMap._atlasSize = sizeHint.Value;
            }
            else
            {
                using ( Stream stream = ResourceManager.OpenStream( imageName,
                    ResourceOpenMode.Read ) )
                {
                    using ( Bitmap bitmap = new Bitmap( stream ) )
                    {
                        var packer = GraphicsImplementation.Instance.CreateImagePacker();
                        imageMap._atlasSize = packer.CalculateSize( bitmap, frameGenerator );
                    }
                }
            }

            if ( ResourceManager.ResourceExists( resourceName ) )
            {
                using ( Stream stream = ResourceManager.OpenStream(
                    resourceName, ResourceOpenMode.TruncateAndWrite ) )
                {
                    imageMap.SaveToXmlStream( stream );
                }
            }
            else
            {
                using ( Stream stream = ResourceManager.CreateResource( resourceName ) )
                {
                    imageMap.SaveToXmlStream( stream );
                }
            }
        }

        public void SaveToXmlStream( Stream stream )
        {
            var sizeConverter = TypeDescriptor.GetConverter( typeof( Size ) );
            Debug.Assert( sizeConverter.CanConvertFrom( typeof( String ) ) );

            Debug.Assert( _frameGenerator != null );

            XDocument doc = new XDocument(
                new XDeclaration( "1.0", "UTF-8", "yes" ),
                new XElement( "ImageMap",
                    new XElement( "ImageName", _imageName ),
                    new XElement( "AtlasSizeHint", 
                        sizeConverter.ConvertToInvariantString( _atlasSize ) ),
                    _frameGenerator.XmlRepresentation
                    )
            );

            using ( TextWriter textWriter = new StreamWriter( stream, Encoding.UTF8 ) )
            {
                doc.Save( textWriter );
            }
        }

        internal void DrawFrame( int frameIndex, Vector2d position, Vector2d scale, Color color,
            bool flipX, bool flipY )
        {
            _frames[frameIndex].DrawFrame( position, scale, color, flipX, flipY );
        }

        internal void DrawFrameRotated( int frameIndex, Vector2d position, float rotation, 
            Vector2d scale, Color color, bool flipX, bool flipY )
        {
            _frames[frameIndex].DrawFrameRotated( position, rotation, scale, color, flipX, flipY );
        }

        internal void DrawFrameInRectangle( int frameIndex, RectangleF position, Color color, 
            bool flipX, bool flipY )
        {
            _frames[frameIndex].DrawFrameInRectangle( position, color, flipX, flipY );
        }

        internal void DrawFrameClippedAndRotated( int frameIndex, Vector2d center, float rotation, 
            Vector2d scale, bool flipX, bool flipY, Color color, RectangleF clipArea )
        {
            _frames[frameIndex].DrawFrameClippedAndRotated( center, rotation, scale, flipX, flipY, 
                color, clipArea );
        }

        /// <summary>
        /// Takes the source image, packs the requested areas in a texture.
        /// </summary>
        /// <param directoryName="sourceImage">The source image</param>
        /// <param directoryName="frameAreas">The frames</param>
        /// <param directoryName="sizeHint">An optional size hint for the atlas texture</param>
        void _packImage( Bitmap sourceImage, IEnumerable<Rectangle> frameAreas, Size? sizeHint )
        {
            try
            {
                var packer = GraphicsImplementation.Instance.CreateImagePacker();
                _frames = packer.PackFrames( sourceImage, frameAreas, sizeHint ).ToList();
            }
            catch ( ImageMapException ex )
            {
                Log.Error( "ImageMap packing error (" + this.ResourceName + "): " +
                    ex.Message );
            }
            finally
            {
                sourceImage.Dispose();
            }
        }

        protected override void _dispose( bool disposing )
        {
            if ( !_disposed )
            {
                if ( disposing )
                {
                    if ( _frames != null )
                    {
                        foreach ( var frame in _frames )
                        {
                            frame.Dispose();
                        }

                        _frames = null;
                    }
                }
                _disposed = true;
            }

            base._dispose( disposing );
        }

        public static Type[] GetFrameGeneratorTypes()
        {
            if ( _frameGeneratorTypes != null )
            {
                return _frameGeneratorTypes.ToArray();
            }

            _frameGeneratorTypes = new List<Type>();

            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();

            foreach ( Assembly asm in assemblies )
            {
                Type[] types = asm.GetExportedTypes();

                foreach ( Type t in types )
                {
                    if ( t.GetInterfaces().Contains( typeof( IFrameGenerator ) ) )
                    {
                        _frameGeneratorTypes.Add( t );
                    }
                }
            }

            return _frameGeneratorTypes.ToArray();
        }

        public static IFrameGenerator CreateFrameGenerator( String xmlName )
        {
            if ( _xmlNameToframeGeneratorType == null )
            {
                _xmlNameToframeGeneratorType = new Dictionary<string, Type>();

                Type[] frameGeneratorTypes = GetFrameGeneratorTypes();

                foreach ( Type type in frameGeneratorTypes )
                {
                    Object inst = TypeDescriptor.CreateInstance( null, type, null, null );
                    IFrameGenerator frameGenerator = (IFrameGenerator) inst;

                    _xmlNameToframeGeneratorType.Add( 
                        frameGenerator.XmlName, 
                        type 
                        );
                }
            }

            Type t;

            if ( _xmlNameToframeGeneratorType.TryGetValue( xmlName, out t ) )
            {
                Object inst = TypeDescriptor.CreateInstance( null, t, null, null );
                return (IFrameGenerator) inst;
            }
            else
            {
                throw new Exception( "Name " + xmlName + " not registered." );
            }
        }

        static List<Type> _frameGeneratorTypes;
        static Dictionary<String, Type> _xmlNameToframeGeneratorType;

        #endregion
    }
}
